package net.oschina.arvin.multi.field.sort;

import java.lang.reflect.Field;

/**
 * 模型排序项， 指定某个属性的排序规则
 *
 * @author Arvin
 * @time 2017/9/30 22:52
 */
@SuppressWarnings({"unchecked"})
public class ModelSortItem extends AbstractSortItem {

    /** 需要排序的字段 */
    private Field sortField;

    public ModelSortItem(Field sortField) {
        this.sortField = sortField;
        if (!this.sortField.isAccessible()) {
            this.sortField.setAccessible(true);
        }
    }

    public ModelSortItem(Field sortField, boolean asc) {
        this.sortField = sortField;
        this.asc = asc;
    }

    public Field getSortField() {
        return sortField;
    }

    @Override
    public int compare(Object o1, Object o2) {
        try {
            Object v1 = this.sortField.get(o1);
            Object v2 = this.sortField.get(o2);
            return compareValue(v1, v2);
        } catch (Exception e) {
            return 0;
        }
    }
}
